<template lang="pug">
div
  div(style='margin-bottom: 20px')
    Button(type='success', icon='plus', shape='circle', @click='showAddForm = true') 新增分类
  table.table
    caption 问题分类管理
    tbody
      tr(v-if='!categories.length')
        td.text-center 没有分类
      tr(v-for='(cate, idx) in categories')
        //- td {{ cate.name }} \#{{ cate.id }}
        td {{ cate.name }}
        td.text-center(width='150')
          Button(type='primary', @click='edit(cate)', size='small') 编辑
          | &nbsp;&nbsp;
          Button(type='error', @click='deleteCategory(idx)', size='small') 删除
  Modal(title='add category', :loading='true', v-model='showAddForm', @on-ok='addCategory', @on-cancel='newItem = ""')
    Input(type='text', v-model='newItem')
  Modal(title='edit category', :loading='true', v-model='showEditForm', @on-ok='editCategory')
    Input(type='text', v-model='selectedItem.name')
</template>

<script>
import { mapState } from 'vuex'
import Api from '@/apis/group'
import store from '@/store'
export default {
  beforeRouteEnter (to, from, next) {
    Api.getGroupCategory(store.state.app.id).then(data => {
      next(vm => {
        vm.categories = data
      })
    })
  },
  data () {
    return {
      showAddForm: false,
      showEditForm: false,
      newItem: '',
      selectedItem: {},
      categories: []
    }
  },
  computed: {
    ...mapState({
      appId: state => state.app.id
    })
  },
  // mounted () {
  //   Api.getGroupCategory(1).then(data => {
  //     console.log(data)
  //     this.categories = data
  //   })
  // },
  methods: {
    edit (item) {
      this.selectedItem = item
      this.showEditForm = true
    },
    addCategory () {
      if (this.newItem && this.newItem.trim()) {
        Api.postGroupCategory(this.appId, this.newItem.trim()).then(data => {
          this.categories.push(data)
          this.newItem = ''
          this.showAddForm = false
          this.$Message.success('添加成功')
        })
      }
    },
    editCategory () {
      // alert(this.selectedItem.id + ':' + this.selectedItem.name)
      Api.patchGroupCategory(this.appId, this.selectedItem.id, this.selectedItem.name).then(() => {
        this.$Message.success('更新成功')
        this.showEditForm = false
      })
    },
    deleteCategory (idx) {
      const cate = this.categories[idx]
      this.$Modal.confirm({
        title: '删除以下分类吗？',
        content: `<strong>${cate.name}<strong>`,
        loading: true,
        onOk: () => {
          Api.deleteGroupCategory(this.appId, cate.id).then(() => {
            this.$Message.success('删除成功')
            this.$Modal.remove()
            this.categories.splice(idx, 1)
          })
        }
      })
    }
  }
}
</script>
